package com.xinenhua.businessserver.personal.subscribe;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.kennyc.view.MultiStateView;
import com.oasis.oasislib.base.BaseFragmentActivity;
import com.oasis.oasislib.utils.DialogUtils;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.Holder;
import com.orhanobut.dialogplus.ViewHolder;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.login.pojo.User;
import com.xinenhua.businessserver.personal.ChangePhone;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 生成物业交割单
 */
@ContentView(R.layout.hetong_confirm)
public class HeTongConfirm extends BaseFragmentActivity {


    @ViewInject(R.id.confirm)
    TextView confirm;


    @ViewInject(R.id.webView)
    BridgeWebView mWebView ;

    @ViewInject(R.id.multiStateView)
    MultiStateView mMultiStateView;

    String id ;

    User user ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String event) {
        LogUtil.e(TAG,"onMessageEvent-----"+event);
        finish();
    }

    @Override
    protected void start() {
        super.start();

        user = Const.getUser();

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.e(TAG,"确认推送合同");

                Holder holder = new ViewHolder(R.layout.hetongconfirm_inputpsw);
                final DialogPlus dialog = DialogPlus.newDialog(HeTongConfirm.this)
                        .setContentBackgroundResource(android.R.color.transparent)
                        .setGravity(Gravity.CENTER)
                        .setContentHolder(holder)
                        .create();

                View holderView = dialog.getHolderView();
                //输入框文本
                final EditText pswedit = (EditText) holderView.findViewById(R.id.editText3);
                //取消
                holderView.findViewById(R.id.textView20).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.e(TAG,"取消");
                        //取消
                        dialog.dismiss();
                    }
                });
                //确认
                holderView.findViewById(R.id.okkk).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.e(TAG,"确认");
                        String psw = pswedit.getText().toString();
                        if(!StringUtils.isBlank(psw)){
                            next(psw);
                        }
                    }
                });

                dialog.show();
            }
        });

        id = getIntent().getStringExtra("id");

        LogUtil.e(TAG,"预览 id----"+id);

        mWebView.getSettings().setJavaScriptEnabled(true);
        String url = Const.yulan+id;
        LogUtil.e(TAG," url----"+url);
        mWebView.loadUrl(url);

        WebSettings webSettings = mWebView.getSettings();
        // 使能JavaScript
        webSettings.setJavaScriptEnabled(true);


        //让网页自适应设备大小
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            }

        });

        mWebView.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {  //表示按返回键时的操作
                        mWebView.goBack();   //后退
                        return true;    //已处理
                    }
                }
                return false;
            }
        });



        mWebView.addJavascriptInterface(new HeTongConfirm.JsJavaBridge(this, mWebView), "$App");

    }


    Dialog dialog ;


    private void next(String psw) {

        dialog = DialogUtils.createLoadingDialog(context) ;
        dialog.show();

        LogUtil.e(TAG,"确认推送合同 电话号码："+psw);
        LogUtil.e(TAG,"确认推送合同 合同id："+id);

        HashMap<String,String> map = new HashMap<>() ;
        map.put("id",id);
        map.put("phone",psw);//将要推送给客户的那个手机号码
        map.put("admin_id",user.getAdmin_id()+"");  //操作人id  在linjia_admin 那个表里面

        Call call = BaseHttp.getCallWithUrlAndData(Const.servicehetongtui,map);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                showMsg(e.getMessage());
                dialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                LogUtil.e(TAG,"return "+ rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                   // String s = BaseHttp.getJsonDataAsString(rr);
//                    JsonParser parser = new JsonParser();
//                    JsonObject asJsonObject = parser.parse(s).getAsJsonObject();
//                    String sign = asJsonObject.get("sign").getAsString();

                    showMsg(BaseHttp.getJsonMsg(rr));
                    //推送成功
                    EventBus.getDefault().post("合同已推送");

                }else {
                    showMsg(BaseHttp.getJsonMsg(rr));
                }

                dialog.dismiss();

            }
        });
    }


    public class JsJavaBridge {

        private Activity activity;
        private BridgeWebView webView;

        public JsJavaBridge(Activity activity, BridgeWebView webView) {
            this.activity = activity;
            this.webView = webView;
        }

        @JavascriptInterface
        public void onFinishActivity(String id) {
            LogUtil.e(TAG,"onFinishActivity id="+id);
            //finish();

            
        }


        @JavascriptInterface
        public void showToast(String msg) {
            LogUtil.e(TAG,"showToast");
            ToastUtils.shortToast(activity,msg);
        }
    }

}
